package com.xnf.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnf.model.behavior.dtos.BehaviorEntryDto;
import com.xnf.model.behavior.pojos.ApBehaviorEntry;
import com.xnf.model.common.dtos.ResponseResult;
import com.xnf.model.common.enums.AppHttpCodeEnum;
import com.xnf.model.search.dtos.UserSearchDto;
import com.xnf.model.search.pojos.ApUserSearch;
import com.xnf.model.search.pojos.ApUserSearchWords;
import com.xnf.model.user.pojos.ApUser;
import com.xnf.search.feign.BehaviorFeign;
import com.xnf.search.mapper.ApUserSearchMapper;
import com.xnf.search.service.ApUserSearchService;
import com.xnf.utils.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by xnf on 2022/3/16.
 */
@Service
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {

    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        //1.检查数据
        if (userSearchDto.getPageSize() > 50) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询行为实体
        ApBehaviorEntry apBehaviorEntry = getEntry(userSearchDto);
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ResponseResult responseResult = mongoQuery(userSearchDto, apBehaviorEntry);
       // ResponseResult jdbcQuery = mongoQuery(userSearchDto, apBehaviorEntry);
        return responseResult;
    }

    @Override
    public ResponseResult delUserSearch(UserSearchDto userSearchDto) {
        //1.检查参数
        if (userSearchDto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApBehaviorEntry entry = getEntry(userSearchDto);
        if (entry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新当前搜索记录的状态  status  0
        mongoDelete(userSearchDto,entry);
        jdbcDelete(userSearchDto,entry);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Async("taskExecutor")
    @Override
    public void insert(Integer entryId, String searchWords) {

        mongoInsert(entryId,searchWords);

        jdbcInsert(entryId,searchWords);
    }

    private ApBehaviorEntry getEntry(UserSearchDto userSearchDto) {
        BehaviorEntryDto dto = new BehaviorEntryDto();
        ApUser apUser = AppThreadLocalUtils.get();
        if (apUser != null && apUser.getId() != null) {
            dto.setUserId(apUser.getId());
        }
        dto.setEquipmentId(userSearchDto.getEquipmentId());
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEntryId(dto.getUserId(),dto.getEquipmentId());
        return apBehaviorEntry;
    }



    private ResponseResult mongoQuery(UserSearchDto userSearchDto,ApBehaviorEntry apBehaviorEntry){
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getEntryId()));
        query.limit(userSearchDto.getPageSize());
        List<ApUserSearchWords> apUserSearchWordses =
                mongoTemplate.find(query, ApUserSearchWords.class);
        return ResponseResult.okResult(apUserSearchWordses);
    }

    private ResponseResult jdbcQuery(UserSearchDto userSearchDto,ApBehaviorEntry apBehaviorEntry){
        IPage pageParam = new Page<>(userSearchDto.getPageNum(), userSearchDto.getPageSize());
        IPage<ApUserSearch> page
                = page(pageParam, Wrappers.<ApUserSearch>lambdaQuery().eq(ApUserSearch::getEntryId, apBehaviorEntry.getEntryId()).eq(ApUserSearch::getStatus, 1));
        return ResponseResult.okResult(page.getRecords());
    }

    private void mongoDelete(UserSearchDto userSearchDto,ApBehaviorEntry entry){
        System.out.println("mongoDelete "+userSearchDto);
        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(entry.getEntryId()).and("keyword").is(userSearchDto.getSearchWords()))
                ,ApUserSearchWords.class);
    }

    private void jdbcDelete(UserSearchDto userSearchDto,ApBehaviorEntry entry){
        //2.更新当前搜索记录的状态  status  0
        update(Wrappers.<ApUserSearch>lambdaUpdate().eq(ApUserSearch::getKeyword,userSearchDto.getSearchWords()).eq(ApUserSearch::getEntryId,entry.getEntryId())
                .set(ApUserSearch::getStatus,0));
    }
    private void mongoInsert(Integer entryId, String searchWords){
        ApUserSearchWords one = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(entryId).and("keyword").is(searchWords)), ApUserSearchWords.class);
        System.out.println("one "+ one);
        if (one != null){
            one.setCreatedTime(new Date());
            mongoTemplate.save(one);
        }else{
            one = new ApUserSearchWords();
            one.setEntryId(entryId);
            one.setKeyword(searchWords);
            one.setCreatedTime(new Date());
            mongoTemplate.save(one);
        }
    }

    private void jdbcInsert(Integer entryId, String searchWords){
        ApUserSearch apUserSearch = getOne(Wrappers.<ApUserSearch>lambdaQuery().eq(ApUserSearch::getEntryId, entryId).eq(ApUserSearch::getKeyword, searchWords));
        if (apUserSearch != null && apUserSearch.getStatus() == 1) {
            return;
        } else if (apUserSearch != null && apUserSearch.getStatus() == 0) {
            apUserSearch.setStatus(1);
            updateById(apUserSearch);
            return;
        }
        apUserSearch = new ApUserSearch();
        apUserSearch.setEntryId(entryId);
        apUserSearch.setStatus(1);
        apUserSearch.setKeyword(searchWords);
        apUserSearch.setCreatedTime(new Date());
        save(apUserSearch);
    }
}
